<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Candy <90candy.com@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

use app\index\model\Users;

define('MYROOTPATH','C:\wamp64\www\zx\public');
define('LIMITMAXNUM', 30);
define('MD6', 'tv');    //自定义加密

//返回json格式的数据
function myJson($status, $msg, $data) {
	return json(array(
			   'status' => $status,
			   'msg'    => $msg,
			   'data'   => $data,
			));
	
}

//手机号格式验证
function checkMobile($mobile) {
	$mobileCheck ='/^[1][34578][0-9]{9}$/';
	return preg_match($mobileCheck,$mobile) == true ? true : false;
}

//用户token验证
function checkToken($token) {
    //验证token
    if (strlen($token) != 32) {
        return myJson(-1, 'token格式错误', '');
    }
    $user = Users::getByUserToken($token);
    if (!$user) {
        return myJson(-1, 'token已失效', '');
    }
    return $user->user_id;
}


/**
 * 发起一个post请求到指定接口
 *
 * @param string $api 请求的接口
 * @param array $params post参数
 * @param int $timeout 超时时间
 * @return string 请求结果
 */
function checkVerifyCode($mobile, $verify_code) {
    // 配置项
    $code = $verify_code;
    $api = 'https://webapi.sms.mob.com';
    $appkey = '1c31313d225c7';//糖果TV Key
//    $appkey = '1975276bb3098';//掌悬 Key
    $json_array = array(
        'appkey' => $appkey,
        'phone'  => $mobile,
        'zone'   => '86',
        'code'   => $verify_code,
    );
    // 发送验证码
    $response = postRequest( $api . '/sms/verify', $json_array);

//    var_dump(json_decode($response, true));
    $status_code = json_decode($response)->status;
    if ($status_code != 200) {
        //return myJson(-1, '验证失败', $status);
        return false;
    }
    //return myJson(1, '验证成功', $status);
    return true;
}

function postRequest( $api, array $params = array(), $timeout = 30 ) {
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $api );
    // 以返回的形式接收信息
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
    // 设置为POST方式
    curl_setopt( $ch, CURLOPT_POST, 1 );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $params ) );
    // 不验证https证书
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
    curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/x-www-form-urlencoded;charset=UTF-8',
        'Accept: application/json',
    ) );
    // 发送数据
    $response = curl_exec( $ch );
    // 不要忘记释放资源
    curl_close( $ch );
    return $response;
}